#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>

#include "ioctl_cmds.h"

int main(int argc, char *argv[]) {
    int qset = 0;
    int quantum = 0;
    int value = -1;
    int err = 0;
    int fd = -1;

    if (argc != 2) {
        printf("Usage: %s /dev/scull0\n", argv[0]);
        return -1;
    }

    fd = open(argv[1], O_RDWR);
    if (fd < 0) {
        printf("open %s failed, error: %s\n", argv[1], strerror(errno));
        return -1;
    }
    printf("reset scull module param\n");
    err = ioctl(fd, SCULL_IOCRESET);
    if (err) {
        printf("reset param failed, error: %s\n", strerror(errno));
        goto out;
    }

    printf("get scull module param\n");
    err = ioctl(fd, SCULL_IOCGQSET, &qset);
    if (err) {
        printf("get qset failed, error: %s\n", strerror(errno));
        goto out;
    }
    printf("\tqset = %d\n", qset);

    qset = 255;
    printf("set scull module param to %d\n", qset);
    err = ioctl(fd, SCULL_IOCSQSET, &qset);
    if (err) {
        printf("set qset failed, error: %s\n", strerror(errno));
        goto out;
    }
    printf("query scull module param\n");
    value = ioctl(fd, SCULL_IOCQQSET);
    if (value < 0) {
        printf("query qset failed, error: %s\n", strerror(errno));
        goto out;
    }
    printf("\tqset = %d\n", value);

    qset *= 2;
    printf("tell scull module param to %d\n", qset);
    err = ioctl(fd, SCULL_IOCTQSET, qset);
    if (err) {
        printf("tell qset failed, error: %s\n", strerror(errno));
        goto out;
    }
    printf("query scull module param\n");
    value = ioctl(fd, SCULL_IOCQQSET);
    if (value < 0) {
        printf("query qset failed, error: %s\n", strerror(errno));
        goto out;
    }
    printf("\tqset = %d\n", value);

out:
    close(fd);
    return 0;
}